package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    //注入reids
    private StringRedisTemplate stringRedisTemplate;
    //构造器注入redis
    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session
        //HttpSession session = request.getSession();
        //1 获取请求头中的token
        String token = request.getHeader("authorization");
        if(StringUtil.isNullOrEmpty(token)){
            //不存在拦截
            return false;
        }
        //2 获取session中的用户
        //Object user = session.getAttribute("user");
        //查询reids中所有的key
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries("user:" + token);
        //将map转换为对象类型
        UserDTO userDTO = BeanUtil.mapToBean(entries, UserDTO.class, true);
        //判断用户是否存在
        if(userDTO == null){
            log.info("拦截到请求{} 不能放行", request.getRequestURI());
            //返回401状态码
            response.setStatus(401);
            return false;
        }
        //存在保存到ThreadLocal
        UserHolder.saveUser(userDTO);
        //刷新token的有限期
        stringRedisTemplate.expire("user:" + token, 30, TimeUnit.MINUTES);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
